//
//  String+Extensions.swift
//  扩展文件
//
//  Created by fuwendong on 2018/2/5.
//  Copyright © 2018年 fuwendong. All rights reserved.
//

import UIKit
import Foundation

// MARK: MD5
extension String {
    /// 计算MD5散列结果
    /**
    计算MD5散列结果
    终端测试命令：
    md5 -s "string"
    提示：随着 MD5 碰撞生成器的出现，MD5 算法不应被用于任何软件完整性检查或代码签名的用途。
    */
    /// - Returns: 32个字符的MD5散列字符串
    func md5() -> String {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize()
        
        return String(format: hash as String)
    }
    /// 给当前文件追加文档路径
    func appemdDocumentDir() -> String? {
        let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last
        
        return dir?.appending("/\(self)")
    }
    /// 给当前文件追加缓存路径
    func appendCacheDir() -> String? {
        let dir = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last
        
        return dir?.appending("/\(self)")
    }
    /// 给当前文件追加临时路径
    func appendTempDir() -> String? {
        let dir = NSTemporaryDirectory()
        
        return dir.appending("/\(self)")
    }
}






























